// move all the code into it's folder
// we are going to fork the process to lighten the load when it start
const { fork } = require('child_process')
const { join } = require('path')
const debug = require('debug')('jsonql-koa:contract-generator')
// try to cache it
let contractCache = {};
/**
 * getContract main
 * @param {object} config options
 * @param {boolean} pub public contract or not
 * @return {object} Promise to resolve the contract json
 */
module.exports = function(config, pub = false) {
  const ps = fork(join(__dirname, 'run.js'))
  const key = pub ? 'public' : 'private';
  if (contractCache[key]) {
    debug(`return ${key} contract from cache`, contractCache[key])
    // this is the problem - if we want to keep it consistent then
    // we should always provide the contract key --> cache is optional!
    // { contract: contractCache[key], cache: true }
    return Promise.resolve(contractCache[key])
  }
  ps.send({ config, pub })
  // return
  return new Promise((resolver, rejecter) => {
    ps.on('message', msg => {
      if (msg.contract) {
        // contractCache[key] = msg.contract; // <-- disable cache
        // return
        return resolver(msg.contract)
      }
      rejecter(msg)
    })
    ps.on('error', err => {
      debug('ps error', err)
      rejecter(err)
    })
  })
}
